let errorCount = 0;
let isGameActive = true;
let highlightedValue = null;
let currentCell = null;

let timerInterval = null;
let startTime = null;
let elapsedTime = 0;

let isPaused = false;
let remainingTimeWhenPaused = 0;

async function newGame() {

    stopTimer();

    elapsedTime = 0;
    startTime = null;
    updateTimerDisplay();

    try {
        isGameActive = true;
        errorCount = 0;
        clearHighlights();
        
        const difficulty = document.getElementById('difficulty').value;
        const response = await fetch('/new-game', {
            method: 'POST',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify({difficulty})
        });
        
        const data = await response.json();
        if (data.error) throw new Error(data.error);
        
        renderBoard(data.puzzle);
        updateStatus('新游戏已开始！', 'success');
    } catch (err) {
        updateStatus(`错误: ${err.message}`, 'error');
    }

    startTimer();
}

function togglePause() {
    if (!isGameActive) return;

    const pauseBtn = document.getElementById('pauseBtn');
    const board = document.getElementById('sudoku-board');
    
    isPaused = !isPaused;
    pauseBtn.classList.toggle('paused');
    board.classList.toggle('paused');

    if (isPaused) {
        // 添加数字隐藏逻辑
        document.querySelectorAll('.sudoku-cell').forEach(c => {
            c.dataset.originalValue = c.value; // 保存原始值
            c.value = ''; // 清空显示
        });
        
        remainingTimeWhenPaused = elapsedTime;
        stopTimer();
        disableAllCells(true);
        updateStatus('游戏已暂停', 'info');
    } else {
        // 恢复数字显示
        document.querySelectorAll('.sudoku-cell').forEach(c => {
            if (c.dataset.originalValue) {
                c.value = c.dataset.originalValue;
                delete c.dataset.originalValue;
            }
        });
        
        startTime = Date.now() - remainingTimeWhenPaused;
        elapsedTime = remainingTimeWhenPaused;
        disableAllCells(false);
        startTimer();
        updateStatus('游戏继续', 'success');
    }
}

// 修改startTimer函数
function startTimer() {
    if (!timerInterval && !isPaused) {
        startTime = Date.now() - elapsedTime;
        timerInterval = setInterval(updateTimer, 1000);
        sessionStorage.setItem('sudokuTimerStart', startTime);
        sessionStorage.setItem('sudokuPaused', 'false');
    }
}

// 修改stopTimer函数
function stopTimer() {
    if (timerInterval) {
        clearInterval(timerInterval);
        timerInterval = null;
        sessionStorage.setItem('sudokuPaused', 'true');
        sessionStorage.setItem('sudokuPausedTime', elapsedTime);
    }
}

function updateTimer() {
    elapsedTime = Date.now() - startTime;
    updateTimerDisplay();
    // 自动保存时间
    sessionStorage.setItem('sudokuTimerElapsed', elapsedTime);
}

function updateTimerDisplay() {
    const totalSeconds = Math.floor(elapsedTime / 1000);
    const minutes = String(Math.floor(totalSeconds / 60)).padStart(2, '0');
    const seconds = String(totalSeconds % 60).padStart(2, '0');
    document.getElementById('timer').textContent = `${minutes}:${seconds}`;
}

// 恢复计时（页面加载时）
function restoreTimer() {
    const savedStart = sessionStorage.getItem('sudokuTimerStart');
    const savedElapsed = sessionStorage.getItem('sudokuTimerElapsed');
    const isPausedState = sessionStorage.getItem('sudokuPaused') === 'true';
    
    if (isPausedState) {
        elapsedTime = parseInt(sessionStorage.getItem('sudokuPausedTime')) || 0;
        isPaused = true;
        document.getElementById('pauseBtn').classList.add('paused');
        document.getElementById('sudoku-board').classList.add('paused');
        updateTimerDisplay();
    } else if (savedStart && savedElapsed) {
        startTime = parseInt(savedStart);
        elapsedTime = parseInt(savedElapsed);
        updateTimerDisplay();
        startTimer();
    }
}

function disableAllCells(disabled) {
    document.querySelectorAll('.sudoku-cell').forEach(c => {
        if (!c.classList.contains('initial')) {
            c.disabled = disabled;
        }
    });
}


function renderBoard(puzzle) {
    let html = '<table class="sudoku-grid">';
    for (let i = 0; i < 9; i++) {
        html += '<tr>';
        for (let j = 0; j < 9; j++) {
            const value = puzzle[i][j] || '';
            const isInitial = puzzle[i][j] !== 0;
            const classes = [
                'sudoku-cell',
                (j % 3 === 2 && j !== 8) ? 'thick-right' : '',
                (i % 3 === 2 && i !== 8) ? 'thick-bottom' : '',
                isInitial ? 'initial' : ''
            ].filter(c => c).join(' ');
            
            html += `
                <td>
                    <input class="${classes}" 
                           type="number"
                           min="1"
                           max="9"
                           value="${value}"
                           data-row="${i}"
                           data-col="${j}"
                           ${isInitial ? 'readonly' : ''}
                           oninput="handleInput(this)"
                           onfocus="highlightPeerNumbers(this)"
                           onblur="clearHighlights()"
                           onmouseover="handleHover(this)"
                           onmouseout="handleHoverEnd(this)">
                </td>
            `;
        }
        html += '</tr>';
    }
    document.getElementById('sudoku-board').innerHTML = html + '</table>';
}

function handleInput(cell) {
    if (!isGameActive) return;
    
    // 输入过滤
    cell.value = cell.value.replace(/[^1-9]/g, '');
    if (cell.value.length > 1) {
        cell.value = cell.value.slice(0, 1);
    }
    
    validateCell(cell);
}

async function validateCell(cell) {
    clearHighlights();
    cell.classList.remove('error');
    
    if (!cell.value) return;
    
    // 唯一解验证
    const userInput = getCurrentState();
    const uniqueRes = await fetch('/check-unique', {
        method: 'POST',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify({userInput})
    });
    
    const {unique} = await uniqueRes.json();
    if (!unique) {
        cell.value = '';
        updateStatus('此操作会导致多解，禁止输入！', 'error');
        return handleError();
    }
    
    // 冲突检查
    const conflicts = checkConflicts(cell);
    if (conflicts.length > 0) {
        cell.classList.add('error');
        conflicts.forEach(c => c.classList.add('error'));
        return handleError();
    }
    
    checkCompletion();
}

function checkConflicts(cell) {
    const conflicts = [];
    const {row, col, value} = getCellData(cell);
    
    document.querySelectorAll('.sudoku-cell').forEach(other => {
        if (other === cell || other.value === '') return;
        const data = getCellData(other);
        if ((data.row === row || data.col === col || sameBox(row, col, data.row, data.col)) 
            && data.value === value) {
            conflicts.push(other);
        }
    });
    
    return conflicts;
}

function handleError() {
    if (++errorCount >= 3) {
        isGameActive = false;
        document.querySelectorAll('.sudoku-cell').forEach(c => c.disabled = true);
        updateStatus('游戏失败！错误次数过多', 'error');
        stopTimer();
    }
    return false;
}

function highlightPeerNumbers(cell) {
    if (!isGameActive) return;
    clearHighlights();
    
    const value = cell.value;
    if (!value) return;

    currentCell = cell;
    highlightedValue = value;
    
    cell.classList.add('current');
    
    document.querySelectorAll('.sudoku-cell').forEach(c => {
        if (c !== cell && c.value === value) {
            c.classList.add('highlight');
        }
    });
}

function clearHighlights() {
    document.querySelectorAll('.highlight, .current').forEach(c => {
        c.classList.remove('highlight', 'current');
    });
    highlightedValue = null;
    currentCell = null;
}

function handleHover(cell) {
    if (isGameActive && !cell.readOnly && !currentCell) {
        highlightPeerNumbers(cell);
    }
}

function handleHoverEnd() {
    if (!currentCell) {
        clearHighlights();
    }
}

async function checkCompletion() {
    const cells = document.querySelectorAll('.sudoku-cell:not(.initial)');
    if ([...cells].every(c => c.value !== '')) {
        const res = await fetch('/validate', {
            method: 'POST',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify({userInput: getCurrentState()})
        });
        const {valid} = await res.json();
        if (valid) {
            stopTimer();
            isGameActive = false;
            updateStatus('恭喜，挑战成功！', 'success');
        }
    }
}

function getCurrentState() {
    const state = Array(9).fill().map(() => Array(9).fill(0));
    document.querySelectorAll('.sudoku-cell').forEach(c => {
        state[c.dataset.row][c.dataset.col] = c.value ? parseInt(c.value) : 0;
    });
    return state;
}

function getCellData(cell) {
    return {
        row: parseInt(cell.dataset.row),
        col: parseInt(cell.dataset.col),
        value: cell.value
    };
}

function sameBox(r1, c1, r2, c2) {
    return Math.floor(r1/3) === Math.floor(r2/3) && 
           Math.floor(c1/3) === Math.floor(c2/3);
}

async function getHint() {
    if (!isGameActive) return;
    
    try {
        const res = await fetch('/hint');
        const {hint} = await res.json();
        if (hint) {
            const cell = document.querySelector(
                `[data-row="${hint.row}"][data-col="${hint.col}"]`
            );
            if (cell && !cell.readOnly) {
                cell.value = hint.value;
                cell.dispatchEvent(new Event('input'));
            }
        }
    } catch (err) {
        updateStatus('获取提示失败', 'error');
    }
}

async function validateCell(cell) {
    clearHighlights();
    cell.classList.remove('error', 'correct'); // 清除旧状态
    
    if (!cell.value) return;

    // 获取当前游戏数据
    const sudokuData = await fetch('/get-current-game').then(r => r.json());
    
    // 即时验证单个单元格
    const row = parseInt(cell.dataset.row);
    const col = parseInt(cell.dataset.col);
    const isValid = sudokuData.solution[row][col] === parseInt(cell.value);

    if (isValid) {
        cell.classList.add('correct');
        updateStatus('输入正确！', 'success');
        checkCompletion(); // 检查是否完成
    } else {
        cell.classList.add('error');
        updateStatus('输入错误', 'error');
        handleError();
    }

    // 额外验证全局唯一性
    const uniqueRes = await fetch('/check-unique', {
        method: 'POST',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify({userInput: getCurrentState()})
    });
    
    const {unique} = await uniqueRes.json();
    if (!unique) {
        cell.value = '';
        updateStatus('此操作会导致多解，禁止输入！', 'error');
        return handleError();
    }
}

function updateStatus(message, type = 'info') {
    const status = document.getElementById('status');
    status.className = `status-${type}`;
    status.textContent = message;
}

// 初始化游戏
document.addEventListener('DOMContentLoaded', () => {
    restoreTimer();
    newGame();
});

